#!/bin/bash

echo "=========================================="
echo "  Building SimpleOS 32-bit Operating System"
echo "=========================================="

# 检查 nasm 是否安装
if ! command -v nasm &> /dev/null; then
    echo "[ERROR] NASM not found! Please install: sudo apt-get install nasm"
    exit 1
fi

# 编译引导扇区
echo "[1/3] Compiling boot sector..."
nasm -f bin boot.asm -o boot.bin
if [ $? -ne 0 ]; then
    echo "[ERROR] Boot sector compilation failed!"
    exit 1
fi
echo "[OK] Boot sector compiled: boot.bin (512 bytes)"

# 编译内核
echo "[2/3] Compiling kernel..."
nasm -f bin kernel.asm -o kernel.bin
if [ $? -ne 0 ]; then
    echo "[ERROR] Kernel compilation failed!"
    exit 1
fi
echo "[OK] Kernel compiled: kernel.bin"

# 创建操作系统镜像
echo "[3/3] Creating OS image..."
cat boot.bin kernel.bin > os-image.bin

# 填充到合适大小 (确保至少10个扇区，即5120字节)
CURRENT_SIZE=$(stat -c%s os-image.bin)
REQUIRED_SIZE=10240  # 20个扇区，确保内核完全加载

if [ $CURRENT_SIZE -lt $REQUIRED_SIZE ]; then
    dd if=/dev/zero bs=1 count=$((REQUIRED_SIZE - CURRENT_SIZE)) >> os-image.bin 2>/dev/null
fi

echo "[OK] OS image created: os-image.bin"
echo ""
echo "Build completed successfully!"
echo "File sizes:"
ls -lh boot.bin kernel.bin os-image.bin | awk '{print "  " $9 ": " $5}'
echo ""
echo "To run the OS, execute: ./run.sh"
echo "Or manually: qemu-system-i386 -drive format=raw,file=os-image.bin"

